package org.javaforever.cookieshop.serviceimpl;

import java.util.List;

import org.javaforever.cookieshop.dao.OrderItemDao;
import org.javaforever.cookieshop.domain.GoodsBean;
import org.javaforever.cookieshop.domain.OrderItemBean;
import org.javaforever.cookieshop.service.GoodsService;
import org.javaforever.cookieshop.service.OrderItemService;
import org.javaforever.cookieshop.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;

@Service
public class OrderItemServiceImpl implements OrderItemService{
	@Autowired
	protected OrderItemDao dao;
	
	@Autowired
	protected GoodsService goodsService;

	@PersistenceContext
	protected EntityManager entityManager;

	@Override
	public void activateAllOrderItems(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.activateOrderItem(id);
        }
	}

	@Override
	public Boolean activateOrderItem(Long id) throws Exception{
        dao.activateOrderItem(id);
        return true;
	}

	@Override
	@Transactional
	public Boolean addOrderItem(OrderItemBean orderItem) throws Exception{
        dao.saveAndFlush(orderItem);
        return true;
	}

	@Override
	public void cloneAllOrderItems(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            cloneOrderItem(id);
        }
	}

	@Override
	public Boolean cloneOrderItem(Long id) throws Exception{
        OrderItemBean orderItem = dao.findOrderItemFullInfoById(id);
        
        String name = orderItem.getName();
        String shortName = name;
        if (name.contains("_") && StringUtil.isInteger(name.substring(name.lastIndexOf('_')+1,name.length()))) {
            shortName = name.substring(0,name.lastIndexOf('_'));
        }
        List<OrderItemBean> names = dao.searchOrderItemIndexedNamesByShortName(shortName);
        int indexNum = 1;
        for (OrderItemBean orderItem0:names) {
            String _name = orderItem0.getName();
            if (_name.contains("_") && StringUtil.isInteger(_name.substring(_name.lastIndexOf('_')+1,_name.length()))) {
                int index = Integer.valueOf(_name.substring(_name.lastIndexOf('_')+1,_name.length()));
                if (index >= indexNum) {
                    indexNum = index + 1;
                }
            }
        }
        String indexName = shortName + "_" + indexNum;
        OrderItemBean orderItem1 = orderItem.clone();
        orderItem1.setId(null);
        orderItem1.setName(indexName);
        addOrderItem(orderItem1);
        return true;
	}

	@Override
	public Integer countActiveOrderItemRecords() throws Exception{
        return dao.countActiveOrderItemRecords();
	}

	@Override
	public Integer countSearchOrderItemsByFieldsRecords(OrderItemBean orderItem) throws Exception{
        String jpql = "select count(*) as countNum from OrderItemBean o where 1=1 ";
        if (orderItem.getName() != null) {
            jpql += " and o.name like CONCAT('%', '"+orderItem.getName()+"','%')";
        }
        if (orderItem.getActive() != null) {
            jpql += " and o.active = "+orderItem.getActive();
        }
        if (orderItem.getPrice() != null && orderItem.getPrice() != 0) {
            jpql += " and abs(o.price - "+orderItem.getPrice()+") < 0.0001";
        }
        if (orderItem.getAmount() != null && orderItem.getAmount() != 0) {
            jpql += " and o.amount = "+orderItem.getAmount();
        }
        if (orderItem.getGoods() != null) {
            jpql += " and o.goods = "+orderItem.getGoods();
        }
        if (orderItem.getCustOrder() != null) {
            jpql += " and o.custOrder = "+orderItem.getCustOrder();
        }
        Query query = entityManager.createQuery(jpql);
        Long count = (Long) query.getSingleResult();
        return count.intValue();
	}

	@Override
	public void deleteAllOrderItems(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.deleteOrderItem(id);
        }
	}

	@Override
	public Boolean deleteOrderItem(Long id) throws Exception{
        dao.deleteOrderItem(id);
        return true;
	}

	@Override
	public OrderItemBean findOrderItemById(Long id) throws Exception{
        return dao.findOrderItemById(id);
	}

	@Override
	public OrderItemBean findOrderItemByName(String name) throws Exception{
        return dao.findOrderItemByName(name);
	}

	@Override
	public List<OrderItemBean> listActiveOrderItems() throws Exception{
        return dao.listActiveOrderItems();
	}

	@Override
	public List<OrderItemBean> listAllOrderItems() throws Exception{
        return dao.listAllOrderItems();
	}

	@Override
	public List<OrderItemBean> searchOrderItemsByFields(OrderItemBean orderItem) throws Exception{
        String jpql = "from OrderItemBean o where 1=1 ";
        if (orderItem.getName() != null) {
            jpql += " and o.name like CONCAT('%', '"+orderItem.getName()+"','%')";
        }
        if (orderItem.getActive() != null) {
            jpql += " and o.active = "+orderItem.getActive();
        }
        if (orderItem.getPrice() != null && orderItem.getPrice() != 0) {
            jpql += " and abs(o.price - "+orderItem.getPrice()+") < 0.0001";
        }
        if (orderItem.getAmount() != null && orderItem.getAmount() != 0) {
            jpql += " and o.amount = "+orderItem.getAmount();
        }
        if (orderItem.getGoods() != null) {
            jpql += " and o.goods = "+orderItem.getGoods();
        }
        if (orderItem.getCustOrder() != null) {
            jpql += " and o.custOrder = "+orderItem.getCustOrder();
        }
        Query query = entityManager.createQuery(jpql);
        List<OrderItemBean> results = query.getResultList();
        return results;
	}

	@Override
	public List<OrderItemBean> searchOrderItemsByFieldsByPage(OrderItemBean orderItem,Integer pagesize,Integer pagenum) throws Exception{
        Integer start = (pagenum-1)*pagesize;
        Integer limit = pagesize;
        String jpql = "from OrderItemBean o where 1=1 ";
        if (orderItem.getName() != null) {
            jpql += " and o.name like CONCAT('%', '"+orderItem.getName()+"','%')";
        }
        if (orderItem.getActive() != null) {
            jpql += " and o.active = "+orderItem.getActive();
        }
        if (orderItem.getPrice() != null && orderItem.getPrice() != 0) {
            jpql += " and abs(o.price - "+orderItem.getPrice()+") < 0.0001";
        }
        if (orderItem.getAmount() != null && orderItem.getAmount() != 0) {
            jpql += " and o.amount = "+orderItem.getAmount();
        }
        if (orderItem.getGoods() != null) {
            jpql += " and o.goods = "+orderItem.getGoods();
        }
        if (orderItem.getCustOrder() != null) {
            jpql += " and o.custOrder = "+orderItem.getCustOrder();
        }
        Query query = entityManager.createQuery(jpql);
        query.setFirstResult(start); // 设置起始位置
        query.setMaxResults(limit); // 设置返回结果数量
        List<OrderItemBean> results = query.getResultList();
        return results;
	}

	public void setDao(OrderItemDao dao){
		this.dao = dao;
	}

	@Override
	public void softDeleteAllOrderItems(String ids) throws Exception{
        String [] idArr = ids.split(",");
        for (String idString : idArr){
            Long id = Long.valueOf(idString);
            dao.softDeleteOrderItem(id);
        }
	}

	@Override
	public boolean softDeleteOrderItem(Long id) throws Exception{
        dao.softDeleteOrderItem(id);
        return true;
	}

	@Override
	public Boolean toggleOneOrderItem(Long id) throws Exception{
        OrderItemBean orderItem = dao.findOrderItemById(id);
        if (orderItem.getActive()==false) {
            dao.toggleOrderItem(id);
        }
        else {
            Integer count = dao.countActiveOrderItemRecords();
            if (count > 1){
                dao.toggleOrderItem(id);
            }
        }
        return true;
	}

	@Override
	public Boolean toggleOrderItem(Long id) throws Exception{
        dao.toggleOrderItem(id);
        return true;
	}

	@Override
	@Transactional
	public Boolean updateOrderItem(OrderItemBean orderItem) throws Exception{
        entityManager.merge(orderItem);
        return true;
	}

	public List<OrderItemBean> selectAllItem(Long orderId) throws Exception{
		List<OrderItemBean> list = dao.selectAllItem(orderId);
		for (OrderItemBean i : list) {
			GoodsBean g = goodsService.findGoodsById(i.getGoods());
			i.setGoodsBean(g);
		}
		return list;
	}
}
